#include "OLModalBackground.h"
#include "OLAppTemplateDefs.h"

#ifdef OL_BLUR_BACKGROUND
#include "OLBackgroundRender.h"
#endif

#include <QtGui/QMouseEvent>
#include <QtGui/QPainter>
#include <QPropertyAnimation>

OLModalBackground::OLModalBackground(QWidget *parent) :
    QWidget(parent), m_opacity(0.0)
#ifdef OL_BLUR_BACKGROUND
    , m_background(0)
#endif
{
}

void OLModalBackground::paintEvent(QPaintEvent* e)
{
    QPainter p(this);
    p.setOpacity(m_opacity);

#ifdef OL_BLUR_BACKGROUND
    p.setPen(Qt::NoPen);
    p.drawPixmap(rect(), *m_background);
#else
    p.setPen(Qt::black);
    p.setBrush(Qt::black);
    p.drawRect(rect());
#endif
}

void OLModalBackground::mousePressEvent(QMouseEvent* e)
{
    if (e->button() != Qt::LeftButton)
        return;
}

void OLModalBackground::mouseReleaseEvent(QMouseEvent* e)
{
    emit clicked();
}

void OLModalBackground::mouseMoveEvent(QMouseEvent* e)
{

}

#ifdef OL_BLUR_BACKGROUND
void OLModalBackground::setBackgroundPixmap(QPixmap& pixmap)
{
    delete m_background;
    m_background = new QPixmap(size());

    OLBackgroundRender* renderer = new OLBackgroundRender(pixmap);
    renderer->resize(size());
    renderer->render(m_background);
}
#endif

bool OLModalBackground::event(QEvent *e)
{
    if(e->type()==QEvent::Show) {
        QPropertyAnimation* anim = new QPropertyAnimation(this, "opacity", this);
        anim->setStartValue(0.0);
        anim->setEndValue(0.9);
        anim->setDuration(500);
        anim->start(QAbstractAnimation::DeleteWhenStopped);
    }

    return QWidget::event(e);
}

void OLModalBackground::setOpacity(qreal opacity)
{
    m_opacity = opacity;
    update();
}

qreal OLModalBackground::opacity()
{
    return m_opacity;
}
